<template>
    <div>
        <div id="editor" type="text/plain" style="width:100%;height:500px"></div>

        <div style="display: none">
            <input ref="uploadImg" type="file" @change="UploadImg">
        </div>
        <Modal
                v-model="shipin"
                title="请填写视频链接"
                @on-ok="sureMovie"
                @on-cancel="cancel">
            <p><Input v-model="shipinlianjie" placeholder="请填写视频地址" /></p>
        </Modal>
    </div>
</template>
<script>
    import './UE/ueditor.config.js';
    import './UE/ueditor.all.min.js';
    import './UE/lang/zh-cn/zh-cn.js';
    import util from '../libs/util';
    import qs from 'qs';

    export default {
        name: 'ue',
        data () {
            return {
                editor: null,
                shipin: false,
                shipinlianjie: ''
            };
        },
        props: {
            value: '',
            config: {}
        },
        mounted () {
            const _this = this;

            this.registerUI('未选择任何文件', '-380px 0', () => {
                this.$refs.uploadImg.click();
            }, 50);
            this.registerUI('未上传视频', '-320px -20px;', () => {
                this.shipin = true;
            }, 51);

            this.editor = window.UE.getEditor('editor', this.config);
            this.editor.addListener('ready', function () {
                _this.editor.setContent(_this.value);
            });
        },
        methods: {
            // 上传图片
            UploadImg () {
                console.log(' this.$refs.uploadImg --->', this.$refs.uploadImg.files);
                console.log('上传图片');
                let _this = this;
                console.log('xxx -->', this.$refs.uploadImg.files[0]);
                let file = this.$refs.uploadImg.files[0];
                console.log('file==>', file);
                let reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = function (e) {
                    let result = this.result;
                    console.log('e -->', e);

                    let uploadLength = 1024 * 200; // 每次传多少KB
                    let timestamp = new Date().getTime();
                    // console.log(typeof this.result);
                    // console.log(this.result);
                    let startIndex = result.indexOf(',') + 1; // 查找数据中逗号以后第一位开始查找

                    result = result.slice(startIndex, result.length); // 查找并截取
                    let imgSize = result.length; // 文件的大小
                    if (result.length !== 0) {
                        _this.zhengZaiShangChuan = true;
                    }
                    let forNum = Math.ceil(imgSize / uploadLength); // 需要切割多少次
                    console.log('总共切多少次', forNum);
                    // console.log('截取完毕', result);
                    // 分片传输图片文件，每次传输1MB大小
                    let imgDataTmp = '';
                    for (let i = 0; i < forNum; i++) {
                        let isStopFlag = false; // 最后一次标识
                        if (forNum - 1 === i) {
                            isStopFlag = true;
                        }
                        console.log(forNum);
                        let startNum = i * uploadLength; // 切片开始位置
                        // console.log('开始位置', startNum);
                        let stopNum = startNum + uploadLength; // 切片结束位置

                        if (isStopFlag) {
                            stopNum = imgSize;
                        }
                        // console.log('结束位置', stopNum);
                        let imgData = result.slice(startNum, stopNum);
                        console.log('切片--》', startNum, stopNum, imgData.length);

                        let postData = {
                            'img_name': file.name,
                            'img_data': imgData,
                            'timestamp': timestamp,
                            'chunk': i,
                            'img_source': 'article'
                        };
                        imgDataTmp += imgData;
                        console.log('imgData -->', imgData);
                        util.ajax.post('/api/img_upload', qs.stringify(postData)).then(resp => {
                            console.log('上传切片成功');
                            if (isStopFlag) {
                                console.log('最后一次');
                                setTimeout(function () {
                                    _this.mergeImg(file, timestamp, forNum);
                                    console.log('最后');
                                }, 500);
                            }
                        }).catch(resp => {
                            console.log('上传切片请求失败');
                        });
                        startNum = stopNum;
                    }
                    console.log('result === imgDataTmp -->', result === imgDataTmp);
                    console.log('imgDataTmp -->', imgDataTmp);
                };
                console.log('传图后', this.dataList);
            },
            mergeImg (file, timestamp, forNum) {
                let _this = this;
                // 发起合并请求
                let postData = {
                    'img_name': file.name,
                    'timestamp': timestamp,
                    'chunk_num': forNum,
                    'img_source': 'article'
                };
                util.ajax.post('/api/img_merge', qs.stringify(postData)).then(resp => {
                    console.log('resp -->', resp);
                    if (resp.data.code === 200) {
                        console.log('合并切片成功');
                        console.log('resp.data.data.img_url -->', resp.data.data.picture_url);
                        let text = '<p style="width: 100%; overflow: hidden"><img width="100%" src="' + util.ajaxUrl + '/' + resp.data.data.picture_url + '"  /></p>';
                        this.editor.execCommand('inserthtml', text);
                    }
                }).catch(resp => {
                    console.log('合并切片请求失败');
                });
            },
            getUEContent () {
                return this.editor.getContent();
            },
            registerUI (name, backgroundPosition, callback, index = 100) {
                window.UE.registerUI(
                    name,
                    function (editor, uiName) {
                        // 注册按钮执行时的command命令，使用命令默认就会带有回退操作
                        editor.registerCommand(uiName, {
                            execCommand: callback
                        });
                        // 创建一个button
                        let btn = new window.UE.ui.Button({
                            // 按钮的名字
                            name: uiName,
                            // 提示
                            title: uiName,
                            // 添加额外样式，指定icon图标，这里默认使用一个重复的icon
                            cssRules: 'background-position: ' + backgroundPosition + ';',
                            // 点击时执行的命令
                            onclick: function () {
                                // 这里可以不用执行命令,做你自己的操作也可
                                editor.execCommand(uiName);
                            }
                        });
                        // 当点到编辑内容上时，按钮要做的状态反射
                        editor.addListener('selectionchange', function () {
                            let state = editor.queryCommandState(uiName);
                            if (state === -1) {
                                btn.setDisabled(true);
                                btn.setChecked(false);
                            } else {
                                btn.setDisabled(false);
                                btn.setChecked(state);
                            }
                        });
                        // 因为你是添加button,所以需要返回这个button
                        return btn;
                    },
                    index
                );
            },
            cancel () {
                this.shipin = false;
                this.shipinlianjie = '';
            },
            sureMovie () {
                let tianjiashipin = '<div style="width: 100%; overflow: hidden"><video width="100%" src="' + this.shipinlianjie + '" controls="controls"></div>';
                this.editor.execCommand('inserthtml', tianjiashipin); // 插入到指定位置
            }
        },
        destroyed () {
            this.editor.destroy();
        }
    };
</script>
